package com.tkmybatis.aop;

import com.alibaba.fastjson.JSON;
import com.tkmybatis.annotation.NoRequestSubmit;
import com.tkmybatis.hfy.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Project_name: tk_mybatis_demo
 * Company: 新致软件
 * Author: ZHU YU WEI
 * Date: Created in 22:46 2021/4/5.
 * Description: NoRequestSubmit定义元注解 两秒内不能重复请求接口，否则报错，频繁请求接口
 * Modified By:
 */

@Component
@Aspect
@Slf4j
public class CntrollerAspect2 {



    //@Pointcut("execution(* com.tkmybatis.controller.*.*(..))")
    @Pointcut("@annotation(com.tkmybatis.annotation.NoRequestSubmit)")
    public void pointCut(){

    }

    /**
     * 防止在两秒内重复请求
     * @param joinPoint
     * @return
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            NoRequestSubmit noRequestSubmit = method.getAnnotation(NoRequestSubmit.class);
            long lockSeconds = noRequestSubmit.lockTime();
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            if(requestAttributes!=null){
                HttpServletRequest request = requestAttributes.getRequest();
                //作为redis的keyz存到缓存里
                String servletPath = request.getServletPath();
                String oldKey=(String)RedisUtils.get(servletPath);
                if(oldKey!=null){
                    log.warn("请求接口有点频繁了，请两分钟后重试重复提交"+servletPath);
                    throw new RuntimeException("请求接口有点频繁了，请两分钟后重试重复提交"+servletPath);
                }
                RedisUtils.set(servletPath,servletPath,lockSeconds);
            }
            String[] parameterNames = methodSignature.getParameterNames();
            log.info("调用传值类型是==== "+ JSON.toJSONString(parameterNames));
            log.info("调用接口传参数为===== "+ JSON.toJSONString(joinPoint.getArgs()));
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
       return null;
    }


}
